import json

import tornado.websocket
import tornado.web

from db import db
from utils.myredis import r
from views.base import BaseHandler
conndict = {}
userlist = []
class WebsockHandler(tornado.websocket.WebSocketHandler):
    # 跨域支持
    def check_origin(self,origin):
        return True
    #建立连接
    def open(self):
        # 获取参数
        id = str(self.get_query_argument('id'))
        name = str(self.get_query_argument('username'))
        print('>>>>>>>',id)
        # 存储链接
        conndict[id] = self
        index = id.find('kefu')
        if index>=0:
            # 判断是否为客服，如果为客服则返回userlist
            self.write_message({'code':"200","userlist":userlist,'mes':{}})
        else:
            # 判断是否为用户，如果为用户加入userlist
            userlist.append({"id":id,'name':name})


    def on_message(self,mes):
        mes = json.loads(mes)
        id = str(mes['id'])
        mes = mes['mes']
        # 如果客服给用户发，判断用户是否在线，如果不在线将消息存入redis key:用户id+"levelmes",values:[]
        conndict[id].write_message({'code':200,'mes':mes,'userlist':userlist})
    def on_close(self):
        pass




class TTHander(tornado.web.RequestHandler):
    def get(self):
        msg = self.get_query_argument('mes')
        id = int(self.get_query_argument('id'))
        conndict[id].write_message(msg)
        print(msg)

















class AddRedisDapeng(BaseHandler):
    def get(self):
        key = "wen"
        # r.del_key(key)
        id = int(self.get_query_argument('id'))
        wen = int(self.get_query_argument('wen'))
        values = str(id) + "." + str(wen)
        r.add_str(key,values)
        return self.finish({
            'code':200,
            'msg':"OK"
        })



import time
class GetDapeng(tornado.web.RequestHandler):
    def get(self):
        id = int(self.get_query_argument('id'))
        key = 'wen'
        lists = []
        while True:
            lists.clear()
            red = r.get_str(key)
            if red:
                aa = red.decode()
                aa.split('.')
                ids = aa[0]
                wendu = aa[2:]
                sql = """select * from dapeng where id=%d""" % int(ids)
                res = db.findAll(sql)
                time.sleep(2)
                for i in res:
                    if int(i['min']) <= int(wendu)  < int(i['max']):
                        status = 0
                        print('>>>>0',status)
                        lists.append({'id': i['id'], 'name': i['name'], "status": status, 'max': i['max'], 'min': i['min'],
                                      "wen": wendu})
                    else:
                        status = 1
                        print('>>>>1',status)
                        lists.append({'id': i['id'], 'name': i['name'], "status": status, 'max': i['max'], 'min': i['min'],
                                      "wen": wendu})
            else:
                sql = """select * from dapeng"""
                res = db.findAll(sql)
                for i in res:
                    lists.append({'id': i['id'], 'name': i['name'], "status": 0, 'max': i['max'], 'min': i['min']})
            conndict[id].write_message(json.dumps(lists))

